#! /usr/bin/env python

'''
[Author]
Davi Vercillo C. Garcia <davivercillo@gmail.com>

[About]
Pifac is an interface for Debian's apt-cache, written in Python 2k.
This interface allows easy manipulation of commands, colored and 
highlighted outputs.

[License]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from popen2 import popen2
from sys import argv, exit
from os import system, getuid
from optparse import OptionParser
from signal import signal, SIG_DFL

VERSION = 0.1
PATH = '/usr/bin/apt-'

MAIN_COLOR = 'red'
VERSION_COLOR = 'yellow'
DESCRIPTION_COLOR = ''
DEPENDENCE_COLOR = 'green'
MESSAGE_COLOR = 'cyan'

def colorize(color, string):
    color_codes = {  'white'  :  '\033[0;29m%s\033[m',\
                     'gray'   :  '\033[0;30m%s\033[m',\
                     'red'    :  '\033[1;31m%s\033[m',\
                     'green'  :  '\033[0;32m%s\033[m',\
                     'yellow' :  '\033[0;33m%s\033[m',\
                     'blue'   :  '\033[0;34m%s\033[m',\
                     'purple' :  '\033[0;35m%s\033[m',\
                     'cyan'   :  '\033[0;36m%s\033[m'    }
    
    try:
        return (color_codes[color] % string)
    except:
        return string

def option_parser():
    parser = OptionParser()
    
    parser.add_option('-D', '--show-dependencies',\
                      action   = 'store_true',\
                      dest     = 'show_dependencies',\
                      default  = False,\
                      help     = "show the package's dependencies.")
    
    parser.add_option('-u', '--update',\
                      action   = 'callback',\
                      callback = update,\
                      help     = "update package database before search.")
    
    parser.add_option('-s', '--search',\
                      action   = 'callback',\
                      callback = search,\
                      nargs    = 1,\
                      help     = "search for a package in apt-cache database.")
    
    return parser.parse_args()

def check_parameter(string):
    for i in [';', '&', '|', '>', '<', '<<', '>>']:
        if i in string:
            return 1
    return 0

def update(option, opt_str, value, parser):
    if not getuid():
        system('%sget update &2> /dev/null' % PATH)
    else:
        print colorize(MESSAGE_COLOR, 'You need to be root to use -u option.')
        exit(-1)

def search(option, opt_str, value, parser):
    if not parser.rargs:
        parser.error('-s option requires an argument.')
    
    string = parser.rargs[0]
    
    if check_parameter(string):
        parser.error('bad parameter.')
    
    search_command = PATH + 'cache search %s'
    info_command = PATH + 'cache show %s | grep "Version:\|Depends:"'
    
    search_output, none = popen2(search_command % string)
    
    print colorize(MESSAGE_COLOR, 'Searching for %s...' % string)
    
    if parser.values.show_dependencies:
        for match in search_output:
            match = match.split(' - ')
            
            info_output, none = popen2(info_command % match[0])
            version = ' [' + info_output.readline().split(': ')[1] + '] '
            dependences = info_output.readline().split(', ')
            
            print (colorize(MAIN_COLOR, match[0]) +\
                   colorize(VERSION_COLOR, version) +\
                   colorize(DESCRIPTION_COLOR, match[1])).replace('\n','')
            
            if len(dependences) > 1:
                print colorize(DEPENDENCE_COLOR,\
                                           dependences[0].replace(': ',':\t'))
                
                for dep in dependences[1:]:
                    print '\t\t' + colorize(DEPENDENCE_COLOR, dep),''
    else:
        for match in search_output:
            match = match.split(' - ')
            
            info_output, none = popen2(info_command % match[0])
            version = ' [' + info_output.readline().split(': ')[1] + '] '
            
            print (colorize(MAIN_COLOR, match[0]) +\
                   colorize(VERSION_COLOR, version) +\
                   colorize(DESCRIPTION_COLOR, match[1])).replace('\n','')

def main():
    signal(2, SIG_DFL)
    (options, args) = option_parser()

if __name__ == "__main__":
    main()

